package com.sayimo.maker.user.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sayimo.framework.exception.DaoException;
import com.sayimo.framework.exception.ServiceException;
import com.sayimo.maker.commons.Constant;
import com.sayimo.maker.commons.utils.JSONUtil;
import com.sayimo.maker.user.dao.ReceivingAddressInterfaceDao;
import com.sayimo.maker.user.service.ReceivingAddressInterfaceService;
import com.sayimo.maker.user.vo.ReceivingAddress;


/**
 * @Copyright (c) 2016 广东省尚一互联网有限公司
 * @Project: maker-user
 * @ClassName: ReceivingAddressInterfaceImplService.java
 * @Description: 收货地址
 * @Author:	tanxin
 * @Date:2017年2月8日,上午11:24:23
 * @Version 1.0.0
 */
@Service(value = "receivingAddressInterfaceImplService")
public class ReceivingAddressInterfaceImplService implements ReceivingAddressInterfaceService {

	private static Log logger = LogFactory.getLog(ReceivingAddressInterfaceImplService.class);

	@Autowired
	private ReceivingAddressInterfaceDao receivingAddressInterfaceImplDao;

	@Autowired
	private HttpServletRequest request;

	private JSONObject buildMap;

	private JSONObject floorMap;

	public ReceivingAddressInterfaceDao getReceivingAddressInterfaceImplDao() {
		return receivingAddressInterfaceImplDao;
	}

	public void setReceivingAddressInterfaceImplDao(ReceivingAddressInterfaceDao receivingAddressInterfaceImplDao) {
		this.receivingAddressInterfaceImplDao = receivingAddressInterfaceImplDao;
	}

	public List<ReceivingAddress> queryAddressByCond(ReceivingAddress address) throws ServiceException {
		try {
			return this.receivingAddressInterfaceImplDao.queryAddressByCond(address);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seeo com.sayimo.school.mall.module.admin.service.
	 * ReceivingAddressInterfaceService #deleteByPrimaryKey(java.lang.Integer)
	 */
	public Map<String, Object> deleteByPrimaryKey(Integer id) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<>();
		try {
			int result = this.receivingAddressInterfaceImplDao.deleteByPrimaryKey(id);
			if (result > 0) {
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, Constant.STATUS_SUCCESS);
				return resultMap;
			}

			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.DATA, Constant.STATUS_ERROR);
			return resultMap;
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.sayimo.school.mall.module.admin.service.
	 * ReceivingAddressInterfaceService #
	 * insertSelective(com.sayimo.school.mall.module.admin.model.
	 * ReceivingAddress )
	 */
	public Map<String, Object> insertSelective(ReceivingAddress address) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<>();
		try {
			if (address.getId() == null || address.getId().equals("")) {
				Integer result = receivingAddressInterfaceImplDao.insertSelective(address);
				if (result != null && result > 0) {
					resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
					resultMap.put(Constant.DATA, Constant.STATUS_SUCCESS);
					return resultMap;
				}
			}
			logger.info("isDefault = " + address.getIsDefault());
			if (StringUtils.isEmpty(request.getParameter("isDefault"))) {
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, Constant.STATUS_SUCCESS);
				return resultMap;
			}

			if (address.getIsDefault() == 1) {
				receivingAddressInterfaceImplDao.updateByPrimaryKeySelective(address);
				ReceivingAddress paramAddress = new ReceivingAddress();
				paramAddress.setCustomerId(address.getCustomerId());
				List<ReceivingAddress> addresses = receivingAddressInterfaceImplDao.queryAddressByCond(paramAddress);
				List<Integer> list = new ArrayList<>();
				for (ReceivingAddress _Address : addresses) {
					logger.info("address.id = " + address.getId() + ", _Address.id = " + _Address.getId());
					if (address.getId() - _Address.getId()!=0) {
						list.add(_Address.getId());
					}
				
				}

				if (CollectionUtils.isNotEmpty(list)) {
					receivingAddressInterfaceImplDao.batchUpdateRecevingAddress(list);
				}

			}

			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, Constant.STATUS_SUCCESS);
			return resultMap;
		} catch (DaoException e) {
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.DATA, Constant.STATUS_ERROR);
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.sayimo.school.mall.module.admin.service.
	 * ReceivingAddressInterfaceService
	 * #updateByPrimaryKeySelective(com.sayimo.school.mall.module.admin.model.
	 * ReceivingAddress)
	 */
	public Map<String, Object> updateByPrimaryKeySelective(ReceivingAddress address) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<>();
		try {

			int result = this.receivingAddressInterfaceImplDao.updateByPrimaryKeySelective(address);
			if (result < 0) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.DATA, Constant.STATUS_ERROR);
				return resultMap;
			}

			logger.info("isDefault = " + address.getIsDefault());
			if (StringUtils.isEmpty(request.getParameter("isDefault"))) {
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, Constant.STATUS_SUCCESS);
				return resultMap;
			}

			if (address.getIsDefault() == 1) {
				ReceivingAddress paramAddress = new ReceivingAddress();
				paramAddress.setCustomerId(address.getCustomerId());
				List<ReceivingAddress> addresses = receivingAddressInterfaceImplDao.queryAddressByCond(paramAddress);
				List<Integer> list = new ArrayList<>();
				Integer addressId = address.getId();
				for (ReceivingAddress _Address : addresses) {
					Integer _AddressId = _Address.getId();
					logger.info("address.id = " + addressId + ", _Address.id = " + _AddressId);
					if (_AddressId - addressId != 0) {
						list.add(_Address.getId());
					}
				}
				if (CollectionUtils.isNotEmpty(list)) {
					receivingAddressInterfaceImplDao.batchUpdateRecevingAddress(list);
				}
			}

			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, Constant.STATUS_SUCCESS);
			return resultMap;
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.sayimo.school.mall.module.admin.service.
	 * ReceivingAddressInterfaceService
	 * #selectDefaultAddress(com.sayimo.school.mall.module.admin.model.
	 * ReceivingAddress)
	 */
	public ReceivingAddress selectDefaultAddress(ReceivingAddress address) throws ServiceException {
		try {
			return this.receivingAddressInterfaceImplDao.selectDefaultAddress(address);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.sayimo.school.mall.module.admin.service.
	 * ReceivingAddressInterfaceService
	 * #getReceiveAddressAPI(com.sayimo.school.mall.module.admin.model.
	 * ReceivingAddress)
	 */
	@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
	public Map getReceiveAddressAPI(ReceivingAddress address) throws ServiceException {

		Map resultMap = new HashMap();
		final List addresses = new ArrayList();
		List<ReceivingAddress> addressesResult = this.queryAddressByCond(address);
		logger.info(".... addressResult = " + JSONUtil.writeValueAsString(addressesResult));

		try {
			if (CollectionUtils.isNotEmpty(addressesResult)) {
				for (ReceivingAddress receivingAddress : addressesResult) {
					Map addressObject = new HashMap();
					addressObject.put("receivingPeople", receivingAddress.getReceivingPeople());
					addressObject.put("telephone", receivingAddress.getTelephone());
					addressObject.put("id", receivingAddress.getId());
					addressObject.put("isDefault", receivingAddress.getIsDefault());
					String place = "";
					String addr = "";
					if (receivingAddress.getPlaceAddress() != null) {
						place = receivingAddress.getPlaceAddress();
					}
					if (receivingAddress.getAddress() != null) {
						addr = receivingAddress.getAddress();
					}
					addressObject.put("address", place  + addr);
					addressObject.put("areaCode",
							receivingAddress.getAreaCode() == null ? "" : receivingAddress.getAreaCode());
					addresses.add(addressObject);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
		resultMap.put(Constant.DATA, new HashMap() {
			{
				put("addresses", addresses);
			}
		});
		return resultMap;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.sayimo.school.mall.module.admin.service.
	 * ReceivingAddressInterfaceService
	 * #getReceiveAddressByIdAPI(com.sayimo.school.mall.module.admin.model.
	 * ReceivingAddress)
	 */
	@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
	public Map getReceiveAddressByIdAPI(ReceivingAddress address) throws ServiceException, DaoException {
		Map resultMap = new HashMap();
		List<ReceivingAddress> addresses = this.queryAddressByCond(address);
		if (CollectionUtils.isEmpty(addresses)) { // 收货地址不存在
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.RECEIVE_ADDRESS_NOT_EXISTS);
			return resultMap;
		}

		ReceivingAddress receivingAddressResult = addresses.get(0);
		final Map dataObject = new HashMap();
		dataObject.put("receivingPeople", receivingAddressResult.getReceivingPeople());
		dataObject.put("telephone", receivingAddressResult.getTelephone());
		dataObject.put("id", receivingAddressResult.getId());
		dataObject.put("isDefault", receivingAddressResult.getIsDefault());
		dataObject.put("address", receivingAddressResult.getAddress());
		dataObject.put("areaCode",
				receivingAddressResult.getAreaCode() == null ? "" : receivingAddressResult.getAreaCode());
		if (receivingAddressResult.getAreaCode() == null) {
			dataObject.put("cityCode", "");
			dataObject.put("provinceCode", "");
		} else {
			dataObject.put("cityCode", receivingAddressResult.getCityCode());
			dataObject.put("provinceCode", receivingAddressResult.getProvinceCode());
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
		resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
		resultMap.put(Constant.DATA, new HashMap() {
			{
				put("address", dataObject);
			}
		});

		return resultMap;
	}

	@Override
	public ReceivingAddress selectMemberDefaultAddress(Integer memberId) throws ServiceException {
		ReceivingAddress receivingAddress = new ReceivingAddress();
		receivingAddress.setCustomerId(memberId);
		ReceivingAddress rAddress = selectDefaultAddress(receivingAddress);
		return rAddress;
	}
}
